# -*- coding: utf-8 -*-

from datetime import datetime, date, timedelta

from django.db import models
from django.contrib.syndication.feeds import Feed as DjangoFeed
from django.contrib.syndication.feeds import FeedDoesNotExist
from django.core.exceptions import ObjectDoesNotExist

from rtve.core.models import Show, ShowTime
import os

# Create your models here.
class Feed(models.Model):
    hash = models.CharField(unique=True, blank=False, max_length=32)
    shows = models.ManyToManyField(Show)

    class Meta:
        db_table = 'Feeds'

    def __unicode__(self):
        return u'Feed %s - %s' % (self.id, self.shows)

    def get_absolute_url(self):
        return '/feeds/shows/%i/' % self.id

class LatestShows(DjangoFeed):
    def get_object(self, bits):
        # In case of "/rss/beats/0613/foo/bar/baz/", or other such clutter,
        # check that bits has only one member.
        if len(bits) != 1:
            raise ObjectDoesNotExist
        return Feed.objects.get(id=bits[0])

    def title(self, obj):
        return 'Programación a la carta'.decode('utf-8')

    def link(self, obj):
        if not obj:
            raise FeedDoesNotExist
        return obj.get_absolute_url()

    def description(self, obj):
        l = []
        for show in obj.shows.all():
            l.append( show.name )
        s = " + ".join(l)
        return "Programación para: %s".decode('utf-8') % s

    def items(self, obj):
        today = date.today()
        one_day = timedelta(days=1)
        tomorrow = today + one_day
        aftertomorrow = tomorrow + one_day
        yesterday = today - one_day

        return ShowTime.objects.filter( show__in = obj.shows.all() ).filter( datetime__range=(tomorrow, aftertomorrow)).order_by('datetime')[:15]
   
    def item_link(self, item):
        if item.show.web: return item.show.web
        else: return 'http://www.rtve.es/television/parrilla/parrilla_television.shtml'

    def item_pubdate(self, item):
        return item.datetime

    def item_guid(self, item):
        import md5 
        s = item.show.name.encode('utf-8') + item.channel.name.encode('utf-8') + item.datetime.__str__()
        return os.environ.get('HOSTNAME') + '/hash/%s/' % md5.new(s).hexdigest()

   
